<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI简历分析</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 配置Tailwind自定义主题 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5',
                        secondary: '#818CF8',
                        neutral: {
                            50: '#F8FAFC',
                            100: '#F1F5F9',
                            200: '#E2E8F0',
                            700: '#334155',
                            800: '#1E293B',
                            900: '#0F172A'
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 10px 15px -3px rgba(0, 0, 0, 0.05), 0 4px 6px -2px rgba(0, 0, 0, 0.03)',
                        'message': '0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)',
                    }
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .message-appear {
                animation: fadeIn 0.3s ease-out;
            }
            .btn-hover {
                @apply transition-all duration-300 hover:shadow-lg transform hover:-translate-y-0.5;
            }
            .chat-container {
                scrollbar-width: thin;
                scrollbar-color: theme('colors.primary/30') theme('colors.neutral.100');
            }
            .chat-container::-webkit-scrollbar {
                width: 6px;
            }
            .chat-container::-webkit-scrollbar-thumb {
                background-color: theme('colors.primary/30');
                border-radius: 3px;
            }
            .file-input-custom {
                @apply block text-sm text-neutral-700
                file:mr-4 file:py-2 file:px-4
                file:rounded-lg file:border-0
                file:text-sm file:font-medium
                file:bg-primary/10 file:text-primary
                hover:file:bg-primary/20 transition-all;
            }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-neutral-50 to-neutral-100 min-h-screen font-sans text-neutral-800">
<!-- 顶部导航 -->
<header class="bg-white/80 backdrop-blur-sm shadow-sm sticky top-0 z-10">
    <div class="max-w-4xl mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-file-text-o text-primary text-xl"></i>
            <h1 class="text-lg font-semibold text-neutral-800">AI简历分析助手</h1>
        </div>
        <div class="flex items-center gap-3">
            <a href="/api/account" class="text-neutral-700 hover:text-primary transition-colors flex items-center gap-1 px-3 py-1.5 rounded-md hover:bg-neutral-100">
                <i class="fa fa-user-circle-o"></i>
                <span>用户管理</span>
            </a>
            <a href="/api/logout" class="text-neutral-700 hover:text-primary transition-colors flex items-center gap-1 px-3 py-1.5 rounded-md hover:bg-neutral-100">
                <i class="fa fa-sign-out"></i>
                <span>退出登录</span>
            </a>
        </div>
    </div>
</header>

<main class="max-w-4xl mx-auto p-4 md:p-6 lg:p-8">
    <!-- 聊天卡片 -->
    <div class="bg-white rounded-2xl shadow-card overflow-hidden transform transition-all duration-300 hover:shadow-lg">
        <!-- 卡片标题区 -->
        <div class="bg-gradient-to-r from-primary to-secondary px-6 py-4">
            <h2 class="text-[clamp(1.25rem,3vw,1.75rem)] font-bold text-white">简历智能分析</h2>
            <p class="text-white/90 text-sm mt-1">上传简历，获取专业分析报告</p>
        </div>

        <!-- 聊天界面 -->
        <div id="chat-container" class="chat-container mb-0 h-[60vh] overflow-y-auto p-4 md:p-6 space-y-4">
            <!-- 欢迎消息 -->
            <div class="flex items-start message-appear">
                <div class="bg-primary text-white p-2.5 rounded-full mr-3 shadow-md">
                    <i class="fa fa-robot text-lg"></i>
                </div>
                <div class="bg-blue-50 p-4 rounded-2xl rounded-tl-none max-w-[85%] shadow-message">
                    <p class="text-neutral-800 leading-relaxed">你好！我是AI简历分析助手，很高兴为你服务。有什么我可以帮助你的吗？</p>
                    <p class="text-xs text-neutral-500 mt-2">今天 09:30</p>
                </div>
            </div>
            <div class="flex items-start message-appear">
                <div class="bg-primary text-white p-2.5 rounded-full mr-3 shadow-md">
                    <i class="fa fa-robot text-lg"></i>
                </div>
                <div class="bg-blue-50 p-4 rounded-2xl rounded-tl-none max-w-[85%] shadow-message">
                    <p class="text-neutral-800 leading-relaxed">为了更好地分析简历，你可以上传简历文件（PDF或Word格式），我会帮你提取和分析关键信息。</p>
                    <p class="text-xs text-neutral-500 mt-2">今天 09:30</p>
                </div>
            </div>
        </div>

        <!-- 分隔线 -->
        <div class="border-t border-neutral-200"></div>

        <!-- 文件上传区域 -->
        <div class="p-6">
            <!-- 文件选择和上传按钮 -->
            <div class="mb-5 flex flex-col sm:flex-row gap-3">
                <label for="resume-file" class="block text-sm font-medium text-neutral-700 mb-2 sm:mb-0">选择简历文件</label>
                <input type="file" id="resume-file" accept=".pdf,.doc,.docx" class="file-input-custom flex-grow">
                <button id="upload-btn" class="bg-primary hover:bg-primary/90 text-white px-5 py-2.5 rounded-lg shadow transition-all duration-300 flex items-center gap-2 btn-hover whitespace-nowrap">
                    <i class="fa fa-upload"></i>
                    <span>上传并分析</span>
                </button>
            </div>
            <div id="file-name" class="text-sm text-neutral-600 mb-4 min-h-[20px]"></div>

            <!-- 消息发送区域 -->
            <div class="flex gap-3 mb-5">
                <input type="text" id="message-input" placeholder="输入你的问题或补充信息..."
                       class="flex-grow px-4 py-2.5 border border-neutral-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                <button id="send-btn" class="bg-primary hover:bg-primary/90 text-white px-5 py-2.5 rounded-lg shadow transition-all duration-300 flex items-center gap-2 btn-hover whitespace-nowrap">
                    <i class="fa fa-paper-plane"></i>
                    <span>发送</span>
                </button>
            </div>

            <!-- 加载状态 -->
            <div id="loading" class="hidden text-primary flex items-center gap-2 p-3 bg-primary/5 rounded-lg border border-primary/10">
                <i class="fa fa-spinner fa-spin"></i>
                <span>正在处理，请稍候...</span>
            </div>

            <!-- 错误信息 -->
            <div id="error-message" class="hidden text-red-600 flex items-center gap-2 p-3 bg-red-50 rounded-lg border border-red-100">
                <i class="fa fa-exclamation-circle"></i>
                <span></span>
            </div>
        </div>
    </div>

    <!-- 页脚信息 -->
    <footer class="mt-6 text-center text-neutral-500 text-sm">
        <p>AI简历分析助手 © 2023 | 保护您的隐私，所有数据仅用于分析</p>
    </footer>
</main>

<script>
    // 存储已上传的简历ID，用于后续消息交互
    let resumeId = null;

    // 添加请求拦截器，为所有请求添加Authorization头
    const originalFetch = window.fetch;
    window.fetch = async function(url, options = {}) {
        const token = localStorage.getItem('jwtToken');
        options.headers = options.headers || {};
        if (token) {
            options.headers['Authorization'] = `Bearer ${token}`;
        }
        return originalFetch(url, options);
    };


    // 页面加载时检查token
    window.addEventListener('load', function() {
        const token = localStorage.getItem('jwtToken');
        console.log('chat页面加载，token存在:', !!token);
        if (!token) {
            window.location.href = '/api/login';
        }
    });

    // 退出登录功能
    document.querySelector('a[href="/api/logout"]').addEventListener('click', function(e) {
        e.preventDefault();
        localStorage.removeItem('jwtToken');
        window.location.href = '/api/login';
    });

    // 获取DOM元素
    const fileInput = document.getElementById('resume-file');
    const fileNameDisplay = document.getElementById('file-name');
    const uploadBtn = document.getElementById('upload-btn');
    const messageInput = document.getElementById('message-input');
    const sendBtn = document.getElementById('send-btn');
    const chatContainer = document.getElementById('chat-container');
    const loadingIndicator = document.getElementById('loading');
    const errorMessage = document.getElementById('error-message');

    // 显示选中的文件名
    fileInput.addEventListener('change', (e) => {
        if (e.target.files.length > 0) {
            fileNameDisplay.textContent = `已选择: ${e.target.files[0].name}`;
        } else {
            fileNameDisplay.textContent = '';
        }
    });

    // 上传文件并处理响应
    uploadBtn.addEventListener('click', async () => {
        const file = fileInput.files[0];

        if (!file) {
            showError('请先选择一个文件');
            return;
        }

        // 验证文件类型
        const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
        if (!allowedTypes.includes(file.type)) {
            showError('请上传PDF或Word格式的文件');
            return;
        }

        try {
            // 显示加载状态
            showLoading(true);
            clearError();

            // 创建FormData对象
            const formData = new FormData();
            formData.append('file', file);

            // 发送文件到后端API
            const response = await fetch('http://localhost:8080/api/resume/upload', {
                method: 'POST',
                body: formData,
                // 注意：上传文件时不要设置Content-Type为application/json
                // 浏览器会自动设置正确的Content-Type和边界
            });

            // 检查响应状态
            if (!response.ok) {
                throw new Error(`HTTP错误，状态码: ${response.status}`);
            }

            // 解析JSON响应
            const result = await response.json();

            // 保存简历ID用于后续交互
            if (result.data && result.data.resumeId) {
                resumeId = result.data.resumeId;
            }

            // 隐藏加载状态
            showLoading(false);

            // 显示上传成功的消息
            addMessageToChat('系统', `已上传文件: ${file.name}`, new Date());

            // 显示分析结果
            displayAnalysisResult(result.data);

        } catch (error) {
            showLoading(false);
            showError(`上传失败: ${error.message}`);
            console.error('上传错误:', error);
        }
    });

    // 发送消息处理
    sendBtn.addEventListener('click', async () => {
        const message = messageInput.value.trim();
        if (!message) {
            showError('请输入消息内容');
            return;
        }

        if (!resumeId) {
            showError('请先上传简历文件');
            return;
        }

        try {
            // 显示用户消息
            addUserMessageToChat(message, new Date());
            messageInput.value = '';

            // 显示加载状态
            showLoading(true);
            clearError();

            // 发送消息到后端API
            // const response = await fetch('http://localhost:8080/api/resume/analyze/query', {
            //     method: 'POST',
            //     headers: {
            //         'Content-Type': 'application/json'
            //     },
            //     body: JSON.stringify({
            //         resumeId: resumeId,
            //         query: message
            //     })
            // });
            // 在发送消息的fetch请求中修改（以temp2.html为例）
            const response = await fetch('http://localhost:8080/api/resume/analyze/query', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    resumeId: resumeId,
                    query: message,
                    userId: currentUserId  // 需要获取当前登录用户ID
                })
            });

            // 检查响应状态
            if (!response.ok) {
                throw new Error(`HTTP错误，状态码: ${response.status}`);
            }

            // 解析JSON响应
            const result = await response.json();

            // 隐藏加载状态
            showLoading(false);

            // 显示分析结果
            displayAnalysisResult(result.data);

        } catch (error) {
            showLoading(false);
            showError(`发送失败: ${error.message}`);
            console.error('发送错误:', error);
        }
    });

    // 按Enter发送消息
    messageInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            sendBtn.click();
        }
    });

    // 显示分析结果
    function displayAnalysisResult(data) {
        if (!data) return;

        let resultHtml = `
                <p class="font-semibold">简历分析结果：</p>
                <p><strong>姓名：</strong>${data.name || '未提供'}</p>
            `;

        // 添加联系方式
        if (data.contact) {
            resultHtml += `
                    <p><strong>联系方式：</strong></p>
                    <ul class="list-disc ml-5">
                        <li>电话：${data.contact.phone || '未提供'}</li>
                        <li>邮箱：${data.contact.email || '未提供'}</li>
                    </ul>
                `;
        }

        // 添加教育经历
        if (data.education && data.education.length > 0) {
            resultHtml += `
                    <p class="mt-2"><strong>教育经历：</strong></p>
                    <ul class="list-disc ml-5">
                `;

            data.education.forEach(edu => {
                resultHtml += `
                        <li>
                            <p>${edu.school} ${edu.major}</p>
                            <p>${edu.time}</p>
                        </li>
                    `;
            });

            resultHtml += `</ul>`;
        }

        // 添加工作经历
        if (data.workExperience && data.workExperience.length > 0) {
            resultHtml += `
                    <p class="mt-2"><strong>工作经历：</strong></p>
                `;

            data.workExperience.forEach(exp => {
                resultHtml += `
                        <div class="ml-5 mt-1">
                            <p><strong>${exp.projectName}</strong> ${exp.time}</p>
                            <p>角色：${exp.role}</p>
                            <p>技术栈：${exp.techStack}</p>
                            ${exp.responsibilities ? `
                                <p>职责：</p>
                                <ul class="list-disc ml-5">
                                    ${exp.responsibilities.map(resp => `<li>${resp}</li>`).join('')}
                                </ul>
                            ` : ''}
                        </div>
                    `;
            });
        }

        // 将结果添加到聊天窗口
        addMessageToChat('AI简历分析', resultHtml, new Date());
    }

    // 添加AI消息到聊天窗口
    function addMessageToChat(sender, content, timestamp) {
        const timeString = timestamp.toLocaleTimeString();
        const messageDiv = document.createElement('div');
        messageDiv.className = 'flex items-start message-appear';
        messageDiv.innerHTML = `
                <div class="bg-primary text-white p-2.5 rounded-full mr-3 shadow-md">
                    <i class="fa fa-robot text-lg"></i>
                </div>
                <div class="bg-blue-50 p-4 rounded-2xl rounded-tl-none max-w-[85%] shadow-message">
                    ${content}
                    <p class="text-xs text-neutral-500 mt-2">${timeString}</p>
                </div>
            `;
        chatContainer.appendChild(messageDiv);
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 添加用户消息到聊天窗口
    function addUserMessageToChat(content, timestamp) {
        const timeString = timestamp.toLocaleTimeString();
        const messageDiv = document.createElement('div');
        messageDiv.className = 'flex items-start justify-end message-appear';
        messageDiv.innerHTML = `
                <div class="bg-neutral-100 p-4 rounded-2xl rounded-tr-none max-w-[85%] shadow-message">
                    ${content}
                    <p class="text-xs text-neutral-500 mt-2">${timeString}</p>
                </div>
                <div class="bg-neutral-200 text-neutral-800 p-2.5 rounded-full ml-3 shadow-md">
                    <i class="fa fa-user text-lg"></i>
                </div>
            `;
        chatContainer.appendChild(messageDiv);
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    // 加载状态控制
    function showLoading(show) {
        loadingIndicator.style.display = show ? 'flex' : 'none';
    }

    // 错误信息控制
    function showError(message) {
        const errorElement = document.getElementById('error-message');
        errorElement.querySelector('span').textContent = message;
        errorElement.style.display = 'flex';

        // 3秒后自动隐藏错误消息
        setTimeout(() => {
            clearError();
        }, 3000);
    }

    function clearError() {
        const errorElement = document.getElementById('error-message');
        errorElement.style.display = 'none';
        errorElement.querySelector('span').textContent = '';
    }
</script>
</body>
</html>